<?php
function sowap($tasks, $host = "m.so.com")
{

    Global $whitelist; /*白名单*/
    Global $posturl;
    Global $filepath;

    $nul = 0;

    /*每页搜索记录*/
    for ($pn = 0; $pn < $tasks['pn']; $pn++) {

        $header = getmobileheader($host);

        $url = "https://m.so.com/s?ajax=1&q=" . str_replace(' ', '%20', $tasks['search']) . "&pn=" . ($pn + 1);

        print_f($url . "\n");

        $contents = Get_Web_Contents($url, 'GET', '', '', $header);

        $text = str_replace(array("\r\n", "\r", "\n"), "", $contents['Body']);

        $text = preg_replace("/<(style|script)(.*?)<\/(style|script)>/i", "", $text);/*去css和js*/
        
        preg_match_all('/class=" ?g-card(.*?)(?=class=" ?g-card)/', $text, $content);
        
        /*每条搜索记录*/
        foreach ($content[0] as $k => $v) {
            
            echo $k,"\t";
            
            preg_match("#\?u=(.*?)&#", $v, $url);/*取网站快照*/

            $url = html_entity_decode(urldecode($url[1]));
            
            if(preg_match('#&u=(.*?)&#', $url, $urls)){
                $url = html_entity_decode(urldecode($urls[1]));
            }
            
            //白名单
            if(!empty($whitelist) && preg_match("#$whitelist#", $url)){
                continue;
            }

            $header = getmobileheader(parse_url($url)['host']);

            $finalsnapshot = Get_Web_Contents($url, 'GET', '', '', $header);

            if (empty($finalsnapshot['Body'])) {
                print_f("快照为空$url\n");
                continue;
            }

            $snapshot = str_replace(array("\r\n", "\r", "\n", "\t"), "", $finalsnapshot['Body']);

            preg_match('/<title.*?>(.*?)<\/title>/i', $snapshot, $data);

            $snapshot = codeWords($snapshot);/*命中词加样式*/

            if (!empty($snapshot)) {
                print_f($data[1]."\n");
                $insert['tasks_id']   = $tasks['id'];
                $insert['tasks_name'] = $tasks['name'];
                $insert['search']     = $tasks['search'];
                $insert['keyword']    = $snapshot['count'];
                $insert['title']      = $data[1];
                $insert['url']        = $url;
                $insert['pn']         = $pn + 1;
                $insert['status']     = 1;
                $insert['addtime']    = time();
                $insert['snapshot']   = $snapshot['snapshot'];
                /*提交*/
                Get_Web_Contents($posturl, 'POST', $insert);
            }else{
                print_f("未命中\n");
            }
        }
        echo "\n";
    }
}
